package com.example.lesson_10_25.controller;

import com.example.lesson_10_25.CommonResult;
import com.example.lesson_10_25.pojo.LoginRequest;
import com.example.lesson_10_25.pojo.TokenResponse;
import com.example.lesson_10_25.pojo.User;
import com.example.lesson_10_25.pojo.VueUser;
import com.example.lesson_10_25.service.UserService;
import com.example.lesson_10_25.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * @PACKAGE_NAME: com.example.lesson_10_25.controller
 * @NAME: UserController
 * @USER: jiang000
 * @DATE: 2023/10/26
 **/
@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    public UserController(UserService userService) {
        this.userService = userService;
    }
    // 登录
    @PostMapping("/login")
    public CommonResult<?> login(@RequestBody LoginRequest loginUser) {
        User user = userService.findOnerByName(loginUser.getUsername());
        if (user == null || !loginUser.getPassword().equals(user.getPassword()) ) {
            return CommonResult.error(50007,"登录失败，账号密码不正确");
        }
//        redisTemplate.opsForValue().set(loginUser.getUsername(), loginUser.getPassword());
        String username = loginUser.getUsername();
        // 生成访问令牌和刷新令牌
        String accessToken = jwtTokenUtil.generateAccessToken(username);
        String refreshToken = jwtTokenUtil.generateRefreshToken(username);
        TokenResponse token_resp = new TokenResponse(accessToken,refreshToken);
        CommonResult<TokenResponse> result = CommonResult.success(token_resp);
        return result;
    }
    // 获取用户名
    @GetMapping("/user/getInfo")
    public CommonResult<?> getUserProfile(@RequestHeader("Authorization") String authHeader) {
        // Bearer refreshToken
        // 解析Authorization请求头中的JWT令牌 Bearer access_token
        if(authHeader == null || authHeader.length() < 8){
            CommonResult<User> result = CommonResult.error(10000, "获取用户失败");
            return result;
        }
        String token = authHeader.substring(7);   // 这一句可能有问题
        String username = jwtTokenUtil.getUsernameFromToken(token);  // 这一句可能有问题
        User user = userService.findOnerByName(username);
        if(user == null){
            CommonResult<User> result = CommonResult.error(10086, "获取用户失败");
            return result;
        }
        CommonResult<User> result = CommonResult.success(user);
        return result;
    }
    // 获取用户列表
    @GetMapping("/user/getUsers")
    public CommonResult<?> getUsers(@RequestHeader("Authorization") String authHeader) {
         if (authHeader == null || authHeader.isEmpty() || authHeader.length() < 8) {
             CommonResult<User> result = CommonResult.error(10000, "获取用户失败");
             return result;
         }
         String token = authHeader.substring(7);
         if (token == null || token.isEmpty()) {
             CommonResult<User> result = CommonResult.error(10000, "获取用户失败");
             return result;
         }
         String username = jwtTokenUtil.getUsernameFromToken(token);
         if (username == null || username.isEmpty()) {
             CommonResult<User> result = CommonResult.error(10000, "获取用户失败");
             return result;
         }
         User user = userService.findOnerByName(username);
         if (user == null) {
             CommonResult<User> result = CommonResult.error(10086, "获取用户失败");
             return result;
         }
         return CommonResult.success(this.userService.selectAllUser());
     }
    @PostMapping("/user/add")
    public CommonResult<?>  addUser(@RequestBody VueUser user) {
        this.userService.addUser(user);
        this.userService.addUserAndRole(user.getUsername(), user.getRole());
        return CommonResult.success("添加用户成功");
    }
    @RequestMapping(value = "/user/delete/{username}", method = RequestMethod.DELETE)
    public CommonResult<?> deleteUser(@PathVariable String username){
        System.out.println(username);
        List<User> user = this.userService.findUserByName(username);
        if(user == null || user.isEmpty()){
        }
        else{
            this.userService.deleteUser(username);
        }
        return CommonResult.success("删除用户成功");
    }

    @RequestMapping(value = "/user/{username}/password", method = RequestMethod.PUT)
    public CommonResult<?> resetUserPassword(@PathVariable String username){
        this.userService.resetUserPassword(username, "123456");
        return CommonResult.success("更新密码成功");
    }
    @RequestMapping(value = "/user/update/{username}", method = RequestMethod.PUT)
    public CommonResult<?> updateUser(@PathVariable String username, @RequestBody VueUser user){
        List<User> users = this.userService.findUserByName(username);
        System.out.println("new Password: " + user.getPassword());
        if(users == null || users.isEmpty()) System.out.println("1111");
        else{
            this.userService.updateUserRole(username,user.getRole());
            this.userService.updateUserEmail(username, user.getEmail());
            this.userService.updateUserPassword(username, user.getPassword());
        }
        return CommonResult.success("更新成功");
    }

}


//    export function addRole(rolename, role) {
//    console.log(role);
//    return request({
//            url: `/role/add/${rolename}`,
//    method: 'put',
//            data: role,
//    })
//}
//    export function updateRole(rolename, role) {
//    console.log(role);
//    return request({
//            url: `/role/update/${rolename}`,
//    method: 'put',
//            data: role,
//    })
//}
